package com.example.demoredis.listener;

import com.example.demoredis.tools.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
 
/**
 * @author zhang
 */
@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
    @Autowired
    private RedisUtil redisUtil;
 
    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }
 
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 获取过期的key
        String expiredKey = message.toString();
        System.out.println(expiredKey);
        // 判断是否是想要监听的过期key
        if (expiredKey.contains("sp")) {
            log.info("redis key过期：{}", expiredKey);
            String id = expiredKey.substring(expiredKey.lastIndexOf(",")+1);
            redisUtil.hdel(id);
        }
 
}
}